﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using prohomework.Models;
using System.IO;
namespace prohomework.Controllers
{
    //    public static bool Hasfile(this HttpPostedFileBase file)
    //{

    //    return (file != null && file.ContentLength > 0) ? true : false;
    //update TeacherCourseWork set 截止日期='2016-11-20' Where 班级代码='FXCX1ZP' and 课程号='02'
    //}

    //测试账号130154495



    public class StudentController : Controller
    {
        //
       // // GET: /Student/
       //public   StudentController() 
       // {
       //   //  returnlogin();

       //   //  return null;
       // }

       //public ActionResult returnlogin()
       //{
       //    // if (Session["username"]) return RedirectToAction("Login", "Account");
       //    //if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
       //    // if (string.IsNullOrEmpty(s1)) return RedirectToAction("Login", "Account");
       //    return null;
       //}


        public ActionResult Index()
        {

            if (Session["username"] == null || Session["username"].ToString()== "") return RedirectToAction("Login", "Account");



          string   sql = "Select * from StudentView where 学号='" + Session["username"]+ "'";
            string ClassID = null, ClassName=null , EnterNum = null, Homepage = null, CourseID=null;
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            if (reader.Read())
            {
              //  teachername = reader[name].ToString();
                ClassID = reader["班级代码"].ToString();
            ClassName = reader["ClassName"].ToString(); 
             EnterNum = reader["登录"].ToString(); 
           Homepage = "spdc.shnu.edu.cn/" + reader["帐号"].ToString(); 

            }
            reader.Close();
            conn.Close();


            ViewData["classname"] = ClassName;
            ViewData["EnterNum"] = EnterNum;
            string courseSql = "Select * from ClassCourseView  Where 班级代码='"+ClassID+"'";
            List<SelectListItem> drowdownlistdata = GetdropdowList(courseSql, "课程号", "课程名称");
            // GetdropdowList(dropdownlistsql, "id", "批阅名称");
            if (drowdownlistdata.Count() > 0)
            {
                ViewData["courselist"] = drowdownlistdata;
             SelectListItem ssd=drowdownlistdata.Find(s=>s.Selected=true);
                CourseID = ssd.Value;
            }
            else
            {
                SelectListItem dd = new SelectListItem();
                dd.Text = "无课程";
                dd.Value = "0";
                dd.Selected = true;
                drowdownlistdata.Add(dd);
                ViewData["courselist"] = drowdownlistdata;
                CourseID = "0";
            }
            string sqlstudent = "Select * from TeacherCourseWork Where 班级代码='"+ClassID+ "' and 课程号='"+CourseID+ "' Order by 布置日期 Desc";
            IEnumerable<studenthomeworkIndex> homeworklist = GetstudenthomeworkList( sqlstudent);
            return View(homeworklist);
        }
        public ActionResult doworknew(string id)
        {
            //string sql= "Select * from homework where ID="+id;
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
            studenthomeworkIndex ss = new studenthomeworkIndex();
            ss = Getworkdata(id);
            if (Stcheckdate(id))
            {
            //    ss = Getworkdata(id);
                ViewData["zuoyemingchen"] = ss.zuoyemingchen;
                ViewData["zuoyemingshuoming"] = ss.zuoyemingshuoming;
                ViewData["homeworkID"] = ss.homeworkID;
                ViewData["message"] = 1;

               
            }
            else
            {
                ViewData["date"] = ss.edndate;

                ViewData["message"] = 0;
            }
            return View();
        }

        public ActionResult modiworknew(string id)
        {


            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");


            studenthomeworkIndex ss = new studenthomeworkIndex();           
            ss = Getworkdata(id);
            string sql = "Select * from sthomework where 学号='" + Session["username"]+"'and HomeworkID=" + id;
             
            if (Stcheckdate(id))
            {
           //     ss = Getworkdata(id);
                          ViewData["datishuoming"]=GetName(sql, "答题说明");
                ViewData["zuoyemingchen"] = ss.zuoyemingchen;
                ViewData["zuoyemingshuoming"] = ss.zuoyemingshuoming;
                ViewData["homeworkID"] = ss.homeworkID;
                ViewData["pic"] = ss.pic;
                ViewData["filecontenttype"] = ss.filecontenttype;
                ViewData["filename"] = ss.filename;
                ViewData["id"] = ss.id;
                ViewData["message"] = 1;
            }
            else
            {
                ViewData["date"] = ss.edndate;

                ViewData["message"] = 0;
            }

          //  string sql = "Select * from sthomework where 学号='"+Session["username"]+"' and HomeworkID="+id;

            return View();

        }
        //
        // GET: /Student/Details/5

        public ActionResult Download(string id)
        {


            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
            string sql = "SELECT FileName, FileContentType, pic FROM Homework WHERE ID='" + id + "'";
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            byte[] filedata = null;
            string fileContentType = null;
            string filename = null;
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                filedata = (byte[])reader["pic"];
                fileContentType = reader["FileContentType"].ToString();
                filename = reader["FileName"].ToString();
            }
            //if (fileContentType == "")
            //{
            //    string fileExtension = Path.GetExtension(filename);
            //    if (fileExtension == ".doc" || fileExtension == ".docx") fileContentType = "application/msword";
            //    else
            //    {
            //        fileContentType = "application/octet-stream";

            //    }

            //}
            reader.Close();
            conn.Close();
            //   var fattach = new FileContentResult(filedata, "application/octet-stream");  
            //  var ss=new file
            return File(filedata, fileContentType, filename);
        }
        public ActionResult showdetail(string id)
        {
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
            string sql ="select pic, fileContentType, fileName from homework where ID='" + id + "'";
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            byte[] filedata = null;
            string fileContentType = null;
            string filename = null;
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                filedata = (byte[])reader["pic"];
                fileContentType = reader["FileContentType"].ToString();
                filename = reader["FileName"].ToString();
            }
            //if (fileContentType == "")
            //{
            //    string fileExtension = Path.GetExtension(filename);
            //    if (fileExtension == ".doc" || fileExtension == ".docx") fileContentType = "application/msword";
            //    else
            //    {
            //        fileContentType = "application/octet-stream";

            //    }

            //}
            reader.Close();
            conn.Close();
            //   var fattach = new FileContentResult(filedata, "application/octet-stream");  
            //  var ss=new file
            return File(filedata, fileContentType);
        }

        //public ActionResult testfile()
        //{

        //    return View();
        //}
        //[HttpPost]
        //public ActionResult testfile(UserProfile model, HttpPostedFileBase file1)
        //{

        //    return View();
        //}
         [HttpPost]
        public ActionResult worksave(string workid, string AnsMemo, int biaoshi, HttpPostedFileBase file1,string add="0")
        {
            //   if()
                    //file2
           // HttpPostedFileBase file1 = Request.Files["upfile"];
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
            if (file1 != null)
            {




                string mimetype = file1.ContentType;
                Stream filestream = file1.InputStream;
                string fileName = Path.GetFileName(file1.FileName);
                int fileLength = file1.ContentLength;
                byte[] fileData = new byte[fileLength];
                filestream.Read(fileData, 0, fileLength);
                string fileExtension = Path.GetExtension(file1.FileName);
                if (fileExtension == ".xls" || fileExtension == ".xlsx") mimetype = "application/vnd.ms-excel";
                if (fileLength > 4194304)
                {
                    var script = String.Format("<script>alert('文件过大！');location.href='{0}'</script>", Url.Action("doworknew", "Student", new { id = workid }));
                    return Content(script, "text/html");
                }

                int ss = updatehomeworkdata(workid, AnsMemo, fileName, mimetype, fileData,add);
                if (ss > 0)
                {
                    if (biaoshi == 1)
                    {
                        var script = String.Format("<script>alert('修改成功！');location.href='{0}'</script>", Url.Action("Index", "Student"));
                        return Content(script, "text/html");
                    }
                    else
                    {
                        var script = String.Format("<script>alert('新作业提交成功！');location.href='{0}'</script>", Url.Action("Index", "Student"));
                        return Content(script, "text/html");
                    }

                }
                else {


                    if (biaoshi == 1)
                    {
                        var script = String.Format("<script>alert('作业修改失败，重新提交！');location.href='{0}'</script>", Url.Action("modiworknew", "Student", new { id = workid, biaoshi = 1 }));
                        return Content(script, "text/html");
                    }
                    else
                    {
                        var script = String.Format("<script>alert('作业提交失败，重新提交！');location.href='{0}'</script>", Url.Action("doworknew", "Student", new { id = workid, biaoshi = 2 }));
                        return Content(script, "text/html");

                    }

                
                }
                    //return RedirectToAction("Index");
            }
            else 
            {

                if (biaoshi == 1)
                {
                    var script = String.Format("<script>alert('作业文件为空！');location.href='{0}'</script>", Url.Action("modiworknew", "Student", new { id = workid, biaoshi=1 }));
                    return Content(script, "text/html");
                }
                else
                {
                    var script = String.Format("<script>alert('作业文件为空！');location.href='{0}'</script>", Url.Action("doworknew", "Student", new { id = workid, biaoshi = 2 }));
                    return Content(script, "text/html");
                }
                //var script = String.Format("<script>alert('文件不能为空！');location.href='{0}'</script>", Url.Action("doworknew", "Student", new { id = workid }));
                //return Content(script, "text/html");
            
            }
            //    return View();
        }


        public ActionResult showwork(string  workid)
        {

            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");

            ViewData["workid"] = workid;
	        var sql="Select * from homework where ID="+ workid;
            var sql2="Select * from stHomeworkView where HomeworkID=" + workid + " and 学号='" + Session["username"] + "'";

            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            showwork ss = new showwork();
            while (reader.Read())
            {

                ss.zuoyehao = reader["次号"].ToString();
                ss.zuoyemingchen = reader["作业名称"].ToString();
                ss.zuoyeshuoming = reader["作业说明"].ToString();

                ss.id = reader["ID"].ToString();
                ss.pic = reader["pic"].ToString();
                ss.filecontenttype = reader["fileContentType"].ToString();
                ss.fileName = reader["fileName"].ToString();
                //filedata = (byte[])reader["pic"];
                //fileContentType = reader["FileContentType"].ToString();
                //filename = reader["FileName"].ToString();
            }
            reader.Close();
            com.CommandText = sql2;
            SqlDataReader reader2 = com.ExecuteReader();
            while (reader2.Read())
            {
                ss.zuoyewenjian = reader2["作业文件"].ToString();
                ss.tijiaoshijian = reader2["提交时间"].ToString();
                ss.piyuemingchen = reader2["批阅名称"].ToString();
                ss.pizhu = reader2["批注"].ToString();
                ss.piyueshijian = reader2["批阅时间"].ToString();
                ss.datishuoming = reader2["答题说明"].ToString();
                

                //filedata = (byte[])reader["pic"];
                //fileContentType = reader["FileContentType"].ToString();
                //filename = reader["FileName"].ToString();
            }

            reader2.Close();
            conn.Close();
            return View(ss);
        }
        public ActionResult homeworkShow(string workid)
        {

            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");

            ViewData["workid"] = workid;
            var sql = "Select * from HomeworkView Where ID=" + workid;

            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            showwork ss = new showwork();
            while (reader.Read())
            {

                ss.zuoyemingchen = reader["作业名称"].ToString();
                ss.buzhiriqi = reader["布置日期"].ToString();
                ss.jiezhiriqi = reader["截止日期"].ToString();

                ss.coursename= reader["CourseName"].ToString();
                ss.fileName = reader["fileName"].ToString();
                ss.filecontenttype = reader["fileContentType"].ToString();
                ss.zuoyeshuoming = reader["作业说明"].ToString();
                ss.id = reader["ID"].ToString();
                ss.AuthorName = reader["AuthorName"].ToString();
                ss.pic = reader["pic"].ToString();
                //filedata = (byte[])reader["pic"];
                //fileContentType = reader["FileContentType"].ToString();
                //filename = reader["FileName"].ToString();
            }
            reader.Close();
            conn.Close();
            return View(ss);
        }
        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Student/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Student/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Student/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Student/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Student/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #region method

        public string GetName(string sql, string name)
        {
            string teachername = "";
            //    string sql = "Select * from teacher where username='"+Session["username"] + "'";
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            if (reader.Read())
            {
                teachername = reader[name].ToString();

            }
            reader.Close();
            conn.Close();
            return teachername;
        }
        public List<SelectListItem> GetdropdowList(string sql, string value, string text)
        {

            //     string sql = "Select * from teacher where username='"+Session["username"] + "'";
            List<SelectListItem> courselist = new List<SelectListItem>();
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            int i = 1;
            while (reader.Read())
            {
                SelectListItem s = new SelectListItem();
                s.Value = reader[value].ToString();
                s.Text = reader[text].ToString();
                if(i==1) s.Selected = true;
                i++;
                courselist.Add(s);
            }
            reader.Close();
            conn.Close();
            return courselist;
        }
        // 检查学生作业的状态
        public bool Stcheckdate(string  homeworkid)
        {
            bool s = true;
            string sql = "Select * from Homework Where id=" + homeworkid;
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            if (reader.Read())
            {
                if (DateTime.Now>Convert.ToDateTime( reader["截止日期"]))
                    s = false;
            }
            reader.Close();
            conn.Close();
            return s;
        }
        public int updatehomeworkdata(string homeworkid, string ansmemo, string filename, string filecontenttype, byte[] filecontent,string add="0")
        {
            int s = -1;
            //string sql = "Select * from Homework Where id=" + homeworkid;
            //SqlConnection conn = new DBConnection().Conn;
            //SqlCommand com = conn.CreateCommand();
            //com.CommandText = sql;
            //conn.Open();
            //SqlDataReader reader = com.ExecuteReader();
            //if (reader.Read())
            //{
            //    if (DateTime.Now > Convert.ToDateTime(reader["截止日期"]))
            //        s = false;
            //}
            //reader.Close();
            //conn.Close();

            //bool b = false;
            if (add == "1")
            {
                string xuehao = Session["username"].ToString();
                string insertdd = "insert into sthomework (HomeworkID,学号) values ('" + homeworkid + "','" + xuehao + "')";
                SqlConnection conn1 = new DBConnection().Conn;
                SqlCommand com1 = conn1.CreateCommand();
                  com1.CommandText = insertdd;
                  conn1.Open();
                  s = com1.ExecuteNonQuery();
            }


            //string sql = "select COUNT(*) from Users where username=@username and userpass=@userpass";
            string sql = "update sthomework  set 答题说明=@ansmemo ,HostIp=@hostip,提交时间=@datetime,filename=@fimename ,fileContentType=@filecontenttype, filecontent=@filecontent where 学号=@username and HomeworkID=@HomeworkID";

            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();

            com.Parameters.Add(new SqlParameter("@username", Session["username"]));
            com.Parameters.Add(new SqlParameter("@HomeworkID",homeworkid));
            com.Parameters.Add(new SqlParameter("@ansmemo", ansmemo));
            com.Parameters.Add(new SqlParameter("@hostip",Request.UserHostAddress.ToString()));
            com.Parameters.Add(new SqlParameter("@datetime",DateTime.Now));
            com.Parameters.Add(new SqlParameter("@fimename", filename));
            com.Parameters.Add(new SqlParameter("@filecontenttype", filecontenttype));
            com.Parameters.Add(new SqlParameter("@filecontent", filecontent));

            com.CommandText = sql;

            conn.Open();
            try
            {
                s= com.ExecuteNonQuery();
            }
            finally
            {
                conn.Close();
            }
            return s;
        }

        public studenthomeworkIndex Getworkdata(string homeworkid)
        {
        //  "Select * from homework where ID=" & Request.QueryString("id"))
            string sql = "Select * from Homework Where id="+homeworkid;
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            studenthomeworkIndex ss = new studenthomeworkIndex();
            if (reader.Read())
            {
                ss.zuoyemingchen = reader["作业名称"].ToString();
                ss.zuoyemingshuoming= reader["作业说明"].ToString();
                ss.edndate = (reader["截止日期"]).ToString();
               ss.homeworkID = reader["id"].ToString();
               if (reader["pic"]==null) ss.pic =null;
               ss.filecontenttype = reader["fileContentType"].ToString();
               ss.filename = reader["fileName"].ToString();
               ss.id = Convert.ToInt32(reader["id"]);
               
            }
            reader.Close();
            conn.Close();
            return ss;
        }

        public bool Stcheckhomework(string stno, string homeworkid)
        {
            bool s = false;
            string sql = "Select * from sthomework where 学号='" +stno+"'and homeworkid="+ homeworkid;
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            if (reader.Read())
            {
                    s = true;
            }
            reader.Close();
            conn.Close();
            return s;
        }





        public IEnumerable<studenthomeworkIndex> GetstudenthomeworkList(string sql)
        {

            //     string sql = "Select * from teacher where username='"+Session["username"] + "'";
            List<studenthomeworkIndex> studenthomeworklist = new List<studenthomeworkIndex>();
            //   List<homeworkIndex> ss = new List<homeworkIndex>();
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                //if (reader["filename"].ToString() !="")
                //{


                studenthomeworkIndex s = new studenthomeworkIndex();
                s.cehao = reader["次号"].ToString();
                s.homeworkID = reader["HomeworkID"].ToString();
                s.checkdatetime = Stcheckdate(s.homeworkID);
                s.checkstudenthomework = Stcheckhomework(Session["username"].ToString(), s.homeworkID);
                s.edndate = reader["截止日期"].ToString();
                s.publishdate= reader["布置日期"].ToString();
                s.zuoyemingchen= reader["作业名称"].ToString();
                
                studenthomeworklist.Add(s);
                //       }
            }
            reader.Close();
            conn.Close();
            return studenthomeworklist as IEnumerable<studenthomeworkIndex>;
        }



        #endregion








    }
}
